package com.mp.approvalreq.dao.impl;

import com.mp.approvalreq.dao.GlobalSettingDao;
import com.mp.approvalreq.entity.po.GlobalSetting;
import com.plusmoney.util.SQLLogger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.*;

/**
 * Created by liuqi on 2018/11/22.
 */
public class GlobalSettingDaoImpl implements GlobalSettingDao {
    private Connection connection;
    private static final Logger logger = LoggerFactory.getLogger(GlobalSettingDaoImpl.class);

    public GlobalSettingDaoImpl(Connection connection) {
        this.connection = connection;
    }

    public Connection getConnection() {
        return connection;
    }

    @Override
    public void insertDuplicateStrategy(GlobalSetting globalSettings) throws SQLException {
        String sql = " insert into request_global_setting set company_id = ?, duplicate_strategy = ? ";
        try (PreparedStatement ps = getConnection().prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
            ps.setInt(1, globalSettings.getCompanyId());
            ps.setInt(2, globalSettings.getDuplicateStrategy());
            logger.info(SQLLogger.logSQL(sql, globalSettings.getCompanyId(), globalSettings.getDuplicateStrategy()));

            ps.executeUpdate();
        }

    }


    @Override
    public GlobalSetting selectGlobalSetting(Integer companyId) throws SQLException {
        GlobalSetting globalSetting = new GlobalSetting();
        String sql = " select id, company_id, duplicate_strategy, financial_flow from request_global_setting " +
                " where company_id = ? limit 1 ";
        try (PreparedStatement ps = getConnection().prepareStatement(sql)) {
            ps.setInt(1, companyId);
            logger.info(SQLLogger.logSQL(sql, companyId));

            try (ResultSet rs = ps.executeQuery()) {
                if (rs.next()) {
                    globalSetting.setId(rs.getInt(1));
                    globalSetting.setCompanyId(rs.getInt(2));
                    globalSetting.setDuplicateStrategy(rs.getInt(3));
                    globalSetting.setFinancialFlow(rs.getString(4));
                }
            }
        }
        return globalSetting;
    }


    @Override
    public void updateDuplicateStrategy(GlobalSetting globalSetting) throws SQLException {
        String sql = " update request_global_setting set duplicate_strategy = ?, financial_flow = ? where company_id = ? limit 1 ";
        try (PreparedStatement ps = getConnection().prepareStatement(sql)) {
            ps.setInt(1, globalSetting.getDuplicateStrategy());
            ps.setString(2, globalSetting.getFinancialFlow());
            ps.setInt(3, globalSetting.getCompanyId());
            logger.info(SQLLogger.logSQL(sql, globalSetting.getDuplicateStrategy(), globalSetting.getFinancialFlow(), globalSetting.getCompanyId()));

            ps.executeUpdate();
        }

    }
}
